#include "menu.hpp"
#include "ui.hpp"

//#define MAN_LOOP_UPDATE
void ManMenu::update(){
	string start = "\033[34";
	string end = "\033[0m";
	string result = "";
	system("clear");
	cout<<"\033[42m" + string(MAN_MENU_OP) +  "\n\033[0m"<<endl;
	for (int i = 0;i < m_list.count; i++) {
		switch(m_list.list[i].state) {
			case MANNON:
				result = "";
				start = "\033[34";
				break;
			case MANPAS:
				result = "PAS";
				start = "\033[32";
				break;
			case MANERR:
				result = "ERR";
				start = "\033[31";
				break;
			default:
				break;
		}
		if(i == m_list.sel)
			start = start + ";7";

	        start = start + "m";
		cout.width(30);
		cout <<start + m_list.list[i].name + ": " ;
		cout.width(10);
		cout << result + end<< endl;
	}
}

void ManMenu::loop(){
#ifdef MAN_LOOP_UPDATE
	while(!m_quit){
		update();
		usleep(1000 * 16); // 60 fps,忽略 update 耗时，粗略计算
	}
#else
	update();

#endif
}

void ManMenu::threadFunc(ManMenu* ptr){
	ptr->loop();
}

void ManMenu::setSel(int sel){
	if(sel >= m_list.count || sel < 0)
		return;
	m_list.sel = sel;
	return;

}

void ManMenu::setState(int state){
	if(state != MANNON && state != MANPAS && state != MANERR)
		return;
	m_list.list[m_list.sel].state = state;
	return;

}

int ManMenu::getSel(){
	return m_list.sel;
}

string ManMenu::getName(){
	return m_list.list[m_list.sel].name;
}

ManMenu::ManMenu(string path){
	string cmd = "ls ";
	vector<string> list;
	cmd += path;
	string result;
	m_quit = false;
	result = cmdPopen(cmd);
	splitStr(result,"\n",list);
	m_list.count = 100;
	if(list.size() < MANMAXLIST)
		m_list.count = list.size();
	system("clear");
	for (int i = 0;i < m_list.count; i++) {
		m_list.list[i].index = i;
		m_list.list[i].state = MANNON;
		m_list.list[i].name = list.at(i);
		cout.width(30);
		cout <<"\033[34m" + list.at(i) + ": " "\033[0m"<< endl;
	}

	m_list.sel = 0;

	m_thread = thread(threadFunc,this);

}

ManMenu::~ManMenu(){
	if (m_thread.joinable()){
		m_thread.join();
	}
}

